<?php

use App\Models\Admin;
use App\Models\MConfig;
use App\Utils\SSUtil;
use Illuminate\Database\Query\Expression;
use Illuminate\Support\HtmlString;

if (!function_exists('mix')) {
    /**
     * Get the path to a versioned Mix file.
     *
     * @param  string $path
     * @return \Illuminate\Support\HtmlString
     *
     * @throws \Exception
     */
    function mix($path)
    {
        static $manifest;
        static $shouldHotReload;

        if (!$manifest) {
            if (!file_exists($manifestPath = public_path('mix-manifest.json'))) {
                throw new Exception('The Mix manifest does not exist.');
            }

            $manifest = json_decode(file_get_contents($manifestPath), true);
        }

        if (!starts_with($path, '/')) {
            $path = "/{$path}";
        }

        if (!array_key_exists($path, $manifest)) {
            throw new Exception(
                "Unable to locate Mix file: {$path}. Please check your " .
                'webpack.mix.js output paths and try again.'
            );
        }

        return $shouldHotReload = file_exists(public_path('hot'))
            ? new HtmlString("http://localhost:8080{$manifest[$path]}")
            : new HtmlString($manifest[$path]);
    }
}

if (!function_exists('cache')) {
    /**
     * 从缓存中读取缓存项
     */
    function cache($key)
    {
        return Cache::get($key);
    }
}

if (!function_exists('onlyNo')) {
    /**
     * 生成14位绝不重复订单号
     *
     * @return string 订单号
     */
    function onlyNo()
    {
        // 1位随机字母 + 随机打乱（6位时间戳 + 1位随机数 + 6位毫秒戳）
        $temp = substr(time(), -6) . random_int(0, 9) . substr(microtime(), 2, 6);
        $temp = str_split($temp);
        shuffle($temp);
        $no = strtoupper(str_random(1)) . implode($temp);
        return $no;     //链接字符串
    }
}

if (!function_exists("inputText")) {
    /**
     * 生成单个表单HTML元素
     * @param string $lable 表单项名称
     * @param int $id id 和 name
     * @param string $type 表单类型
     * @param string $value 表单默认值
     * @param string $intro 表单提醒字符
     * @return Expression
     */
    function inputText($lable, $id, $type, $value, $intro = "")
    {
        $html = <<<HTML
    <li>
        <label class="lable">$lable</label>
        <input id="$id" name="$id" type="$type"
            class="dfinput" value="$value"/>
        <i for="$id">$intro</i>
    </li>
HTML;
        return new Expression($html);
    }
}

if (!function_exists("inputTextArea")) {
    /**
     * 生成单个TextArea表单项
     * @param string $lable 表单项名称
     * @param int $id id 和 name
     * @param string $value 表单默认值
     * @param string $intro 表单提醒字符
     * @return Expression
     */
    function inputTextArea($lable, $id, $value, $intro = "")
    {
        $html = <<<HTML
    <li>
        <label class="lable">$lable</label>
        <textarea id="$id" name="$id" class="textinput" 
            style="margin-top: 10px;">$value</textarea>
        <i for="$id">$intro</i>
    </li>
HTML;
        return new Expression($html);
    }
}

if (!function_exists("inputSelect")) {
    /**
     * 生成单个Select表单项
     * @param string $lable 表单项名称
     * @param int $id id 和 name
     * @param array $array [value="值",title="标题",selected=是否选中]
     * @param string $intro 表单提醒字符
     *
     * @return Expression
     */
    function inputSelect($lable, $id, $array, $intro = "")
    {
        $html = <<<HTML
    <li>
        <label class="lable">$lable</label>
        <select id="$id" name="$id">
HTML;
        foreach ($array as $item) {
            if (isset($item['selected']) && $item['selected']) {
                $html .= "<option value=\"$item[value]\" selected=\"true\">$item[title]</option>";
            } else {
                $html .= "<option value=\"$item[value]\">$item[title]</option>";
            }
        }
        $html .= <<<HTML
        </select>
        <i for="$id">$intro</i>
    </li>
HTML;
        return new Expression($html);
    }
}

if (!function_exists("inputRow")) {
    /**
     * 生成单行多个input标签
     * @param string $lable 表单项名称
     * @param array $array [type="类型",id=name,value="默认值",des="鼠标放上提醒"]
     * @param string $intro 提醒字符串
     * @return Expression
     */
    function inputRow($lable, $array, $intro = "")
    {
        $html = "<li><label class=\"lable\">$lable</label>";
        foreach ($array as $item) {
            $html .= "<div class=\"sm-input\">";
            $html .= "<input id=\"$item[id]\" name=\"$item[id]\" type=\"$item[type]\" 
                         class=\"dfinput calc\" value=\"$item[value]\"/>&nbsp;&nbsp;&nbsp;&nbsp;";
            $html .= "<i class=\"des calc-text\">$item[des]</i>";
            $html .= "</div>";
        }
        $html .= "<i>$intro</i></li>";
        return new Expression($html);
    }
}

if (!function_exists("getFileSize")) {
    /**
     * 获取文件大小文字描述
     *
     * @param string $filename 文件绝对路径
     * @return string 返回文件大小文字描述
     */
    function getFileSize($filename)
    {
        $filesize = filesize($filename);
        if ($filesize >= 1073741824) {
            return round($filesize / 1073741824 * 100) / 100 . ' Gb';
        } elseif ($filesize >= 1048576) {
            return round($filesize / 1048576 * 100) / 100 . ' Mb';
        } elseif ($filesize >= 1024) {
            return round($filesize / 1024 * 100) / 100 . ' Kb';
        } elseif ($filesize > 0) {
            return $filesize . ' Bytes';
        } else {
            return "0 Kb";
        }
    }
}

if (!function_exists("filesOrderByTime")) {
    /**
     * 按时间排序打开目录
     *
     * @param string $dir 目录绝对路径
     * @return array 文件列表数组 相对路径
     */
    function filesOrderByTime($dir)
    {
        $dh = @opendir($dir); // 打开目录，返回一个目录流

        $files = array();

        while ($file = @readdir($dh)) { // 循环读取目录下的文件
            if ($file != '.' && $file != '..' && $file != '.gitkeep' && $file != '.gitignore') {
                $path = $dir . '/' . $file; // 设置目录，用于含有子目录的情况
                if (is_file($path)) {
                    $filetime[] = date("Y-m-d H:i:s", filectime($path)); // 获取文件最近修改日期
                    array_push($files, $file);
                }
            }
        }
        @closedir($dh); // 关闭目录流

        if (isset($filetime)) {
            array_multisort($filetime, SORT_DESC, SORT_STRING, $files);    //按时间排序
        }

        $return = array();
        foreach ($files as $file) {
            $path = $dir . '/' . $file; // 设置目录，用于含有子目录的情况
            $data['file_name'] = $file;
            $data['file_size'] = getFileSize($path);
            $data['create_time'] = date("Y-m-d H:i:s", filectime($path));
            $return[] = $data; //只记录相对路径
        }

        return $return;
    }

}

if (!function_exists("uStatusStr")) {
    /**
     * 用户会员状态的文字描述
     *
     * @param int $status status字段
     * @return string 文字描述
     */
    function uStatusStr($status)
    {
        if ($status == 0) {
            return "正常";
        } elseif ($status == 1) {
            return "已禁用";
        } elseif ($status == 2) {
            return "已冻结";
        } elseif ($status == 3) {
            return "禁用 + 冻结";
        }
        return "异常";
    }
}

if (!function_exists("uVipBdb")) {
    /**
     * 激活会员所需要报单币
     * @param int $vip vip字段
     * @return float 金额
     * @throws Exception
     */
    function uVipBdb($vip)
    {
        if ($vip == \App\Models\MUser::$VIP_1) {
            return 1000;
        } elseif ($vip == \App\Models\MUser::$VIP_2) {
            return 2000;
        } elseif ($vip == \App\Models\MUser::$VIP_3) {
            return 3000;
        } elseif ($vip == \App\Models\MUser::$VIP_4) {
            return 4000;
        } else {
            throw new Exception("未知的会员等级！");
        }
    }
}

if (!function_exists("uBdzxStr")) {
    /**
     * 会员的报单中心身份文字描述
     * @param int $status
     * @return string 文字描述
     */
    function uBdzxStr($status)
    {
        if ($status == \App\Models\MUser::$BDZX_YES) {
            return "报单中心";
        } elseif ($status == \App\Models\MUser::$BDZX_APPLY) {
            return "报单中心申请中";
        } elseif ($status == \App\Models\MUser::$BDZX_NO) {
            return "";
        }
        return "异常";
    }
}

if (!function_exists("loginTheme")) {
    /**
     * 获取登录页面主题
     *
     * 如果未设置主题，则默认使用第一个主题
     */
    function loginTheme()
    {
        $allTheme = config('logintheme.list');

        foreach ($allTheme as $theme) {
            if ($theme['key'] == cv("theme.name")) {
                return $theme;
            }
        }
        return $allTheme[0];
    }
}

if (!function_exists("tbFont")) {
    /**
     * 获取淘宝字体库的网络字体地址
     */
    function tbFont()
    {
        return env("APP_WEB_FONTS");
    }
}

if (!function_exists("backupDB")) {
    /**
     * 备份数据库
     * @return bool 是否执行成功
     */
    function backupDB()
    {
        $u = env("DB_USERNAME");
        $p = env("DB_PASSWORD");
        $db = env("DB_DATABASE");

        $filename = public_path('sqls\\') . date('Y-m-d__H点i分') . ".sql";
        $cmd = "mysqldump --opt -Q -u$u -p$p --default-character-set=utf8 $db > $filename";
        exec($cmd, $response);
        return true;
    }
}

if (!function_exists("countByMoneyLog")) {
    /**
     * 从系统资金统计表获取指定字段的相加总数
     * @param $field    字段名称
     * @return string   返回字段所有值相加总数，并保留两位小数
     */
    function countByMoneyLog($field)
    {
        $data = \App\Models\MMoneyLog::all([$field]);
        $arr = [];

        foreach ($data as $k => $item) {
            $arr[$k] = $item->$field;
        }
        return sprintf("%.2f", array_sum($arr));
    }
}

if (!function_exists("countByWithdrawLog")) {
    /**
     * 从提现记录表获取指定字段的相加总数
     * @param $field    字段名称
     * @return string   返回字段所有值相加总数，并保留两位小数
     */
    function countByWithdrawLog($field)
    {
        $data = \App\Models\MWithdrawLog::all([$field]);
        $arr = [];

        foreach ($data as $k => $item) {
            $arr[$k] = $item->$field;
        }
        return sprintf("%.2f", array_sum($arr));
    }
}

if (!function_exists("tax_count")) {
    /**
     * 系统总税收统计函数
     * @return string
     */
    function tax_count()
    {
        //奖金税收统计
        $bonus_tax = \App\Models\MBonusLog::all(['money_tax']);
        $bonus_arr = [];
        foreach ($bonus_tax as $k => $item) {
            $bonus_arr[$k] = $item->money_tax;
        }
        $bonus_tax_count = array_sum($bonus_arr);

        //提现税收统计
        $withdraw_tax = \App\Models\MWithdrawLog::all(['tax_money']);
        $withdraw_arr = [];
        foreach ($withdraw_tax as $k => $item) {
            $withdraw_arr[$k] = $item->tax_money;
        }
        $withdraw_tax_count = array_sum($withdraw_arr);

        //币种转换税收统计
        $switch_tax = \App\Models\MSwitchCoinLog::all(['tax_money']);
        $switch_arr = [];
        foreach ($switch_tax as $k => $item) {
            $switch_arr[$k] = $item->tax_money;
        }
        $switch_tax_count = array_sum($switch_arr);

        return sprintf("%.2f", $bonus_tax_count + $withdraw_tax_count + $switch_tax_count);
    }
}

if (!function_exists("user_attr")) {
    /**
     * 查找权限数组
     * @param $limit 要查找的权限
     * @return array|bool
     */
    function user_attr($limit)
    {
        $objs = \App\Models\MUserAttr::where('enable', 1)->get();
        if ($objs->isEmpty()) {//判断集合是否为空
            return false;
        }
        $marks = array();
        for ($i = 0; $i < count($objs); $i++) {
            $flag = unserialize($objs[$i]->flag);
            foreach ($flag as $k => $v) {
                if ($k == $limit && $v == 1) {
                    $marks[] = \App\Models\MUserAttr::where('mark', $objs[$i]->mark)->first();
                }
            }
        }
        return $marks;
    }
}

if (!function_exists("ss")) {
    /**
     * 存储数据到Session当中
     * @param string|array $key 可以为Key或者数组，为数组则代表存入一组数据到Session
     * @param string $value $
     * @return string|null
     */
    function ss($key, $value = "")
    {
        if (empty($value) && !is_array($key)) {
            return SSUtil::get($key);
        } else {
            SSUtil::put($key, $value);
        }
    }
}

if (!function_exists("cv")) {
    /**
     * 获取系统配置项精简函数
     * @param string $key title.key 配置项名称.配置项键名
     * @param mixed $default 默认值
     * @param boolean $bool 是否使用原生取值方法
     * @return mixed
     */
    function cv($key, $default = "", $bool = false)
    {
        if (!$bool) {
            return MConfig::getAttr($key, $default);
        }
        $key = explode(".", $key);
        $title = $key[0];
        $key = $key[1];

        $mysql_conf = [
            'host' => env("DB_HOST"),
            'db' => env("DB_DATABASE"),
            'db_user' => env("DB_USERNAME"),
            'db_pwd' => env("DB_PASSWORD")
        ];

        $mysqli = new mysqli($mysql_conf['host'], $mysql_conf['db_user'], $mysql_conf['db_pwd'], $mysql_conf['db']);

        //诊断连接错误
        if ($mysqli->connect_errno) {
            die("could not connect to the database:\n" . $mysqli->connect_error);
        }

        $mysqli->query("set names 'utf8';");    //编码转化

        $sql = "select kv from lara_configs where title = '$title'";

        $send = $mysqli->query($sql);    //发送sql语句

        $res = $send->fetch_object();   //将结果集解析成对象
        if (empty($res)) {
            return '';
        }
        $arr = unserialize($res->kv);
        $mysqli->close();

        return $arr[$key];
    }
}

if (!function_exists("uWalletStr")) {
    function uWalletStr($w)
    {
        if ($w == \App\Models\MWallet::$WALLET_TYPE_1) {
            return "奖金币";
        } elseif ($w == \App\Models\MWallet::$WALLET_TYPE_2) {
            return "报单币";
        } elseif ($w == \App\Models\MWallet::$WALLET_TYPE_3) {
            return "购物币";
        } elseif ($w == \App\Models\MWallet::$WALLET_TYPE_4) {
            return "重消积分";
        } elseif ($w == \App\Models\MWallet::$WALLET_TYPE_5) {
            return "可用积分+可用余额";
        } else {
            throw new Exception("钱包类别异常！");
        }
    }
}

if (!function_exists("uPayWayStr")) {
    function uPayWayStr($w)
    {
        if ($w == \App\Models\MWithdrawLog::$PAY_TYPE_ZFB) {
            return "支付宝";
        } elseif ($w == \App\Models\MWithdrawLog::$PAY_TYPE_WX) {
            return "微信";
        } elseif ($w == \App\Models\MWithdrawLog::$PAY_TYPE_YHK) {
            return "银行卡";
        } else {
            throw new Exception("支付类别异常！");
        }
    }
}

if (!function_exists("ini")) {
    /**
     * 从INI配置文件读取配置项
     * @param $key 配置项名称
     * @param string $default 默认值
     * @return mixed
     */
    function ini($key, $default = "")
    {
        return \App\Utils\INIUtil::ini($key, $default);
    }

}


function uVipByMoney($vip)
{
    if ($vip == \App\Models\MUser::$VIP_1) {
        return 1000;
    } elseif ($vip == \App\Models\MUser::$VIP_2) {
        return 2000;
    } elseif ($vip == \App\Models\MUser::$VIP_3) {
        return 3000;
    } elseif ($vip == \App\Models\MUser::$VIP_4) {
        return 4000;
    } else {
        throw new Exception("未知的会员等级！");
    }
}

/**
 * 获得报单所需奖金币和报单币
 * $flag 0 奖金币  1 报单币
 */
function getBdb($flag)
{
    if ($flag == 0) {
        $money = cv("bonus.bdzx_money") * cv("bonus.bd_jjb") / 100;
    } else if ($flag == 1) {
        $money = cv("bonus.bdzx_money") * cv("bonus.bd_bdb") / 100;
    }
    return $money;
}

/**
 * @param $id
 * @return mixed
 */
function getRemitMoney($id)
{
    return \App\Models\MRemitLog::where("uid", $id)->orderBy("create_time", 'desc')->first();
}

/**
 * @param $id
 * @return mixed 根据地区的id获取地区名称
 */
function getAreaById($id)
{
    return \App\Models\MArea::where("id", $id)->first()->name;
}

/**
 * @param $id
 * @return mixed
 */
function getUserNameById($id)
{
    return \App\Models\MUser::where("id", $id)->first()->username;
}

/**
 * @param $id根据vip获取奖励
 * @return mixed
 */
function getVipAwardByVip($id)
{
    if (intval($id) == 0) {
        return "这是vip会员奖励";
    } else {
        return \App\Models\MVip_award::where("id", $id)->first()->award;
    }

}

if (!function_exists("uVipStr")) {
    /**
     * 会员的VIP身份文字描述
     *
     * @param int $vip vip字段
     * @return string 文字描述
     */
    function uVipStr($vip)
    {
        if ($vip == \App\Models\MUser::$VIP_0) {
            return "普通会员";
        } else {
            return \App\Models\MVip_award::where('vip', $vip)->first()->name;
        }
    }
}

if (!function_exists("uAddrStr")) {
    /**
     * 会员的VIP身份文字描述
     *
     * @param int $vip vip字段
     * @return string 文字描述
     */
    function uAddrStr($id)
    {
        $my_Addr = \APP\Models\MAddress::where('uid', $id)->first();
        $province = \App\Models\MArea::find(intval($my_Addr->province))['name'];
        $city = \App\Models\MArea::find(intval($my_Addr->city))['name'];
        $county = \App\Models\MArea::find(intval($my_Addr->county))['name'];
        $str = $province . $city . $county . $my_Addr->addr;
        return $str;
    }
}

if (!function_exists("cfg")) {
    /**
     * 获取系统配置项
     * @param string $kv
     * @param mixed $default
     * @return mixed 返回读取到的配置项
     */
    function cfg($kv, $default = "")
    {
        return MConfig::getObject($kv, $default);
    }
}

/**
 * @return mixed
 */
function getDomainName()
{
    $domain_name = $_SERVER["SERVER_NAME"];
    return $domain_name;
}

/**
 * @return string 获取从项目名 -到 trunk 路径
 */
function public_url()
{
    $url = public_path();
    $arrs = explode("\\", $url);

    foreach ($arrs as $key => $value) {
        if ($value == "public") {
            return $arrs[$key - 1] . "/" . $arrs[$key];
        }
    }
}

/**
 * 用户名（支持中文）、邮箱、手机账号中间字符串以*隐藏
 * @param $str
 * @return mixed|string
 */
function hideStr($str)
{
    $result = '';
    if (!$str) {
        return $result;
    }
    if (strpos($str, '@')) {
        $email_array = explode("@", $str);
        $prevfix = (strlen($email_array[0]) < 4) ? "" : substr($str, 0, 3); //邮箱前缀
        $count = 0;
        $str = preg_replace('/([\d\w+_-]{0,100})@/', '***@', $str, -1, $count);
        $result = $prevfix . $str;
    } else {
        $pattern = '/(1[34578]{1}[0-9])[0-9]{4}([0-9]{4})/i';
        if (preg_match($pattern, $str)) {
            $result = preg_replace($pattern, '$1****$2', $str); // substr_replace($name,'****',3,4);
        } else {
            $strlen = mb_strlen($str, 'utf-8');
            $firstStr = mb_substr($str, 0, 1, 'utf-8');
            $lastStr = mb_substr($str, -1, 1, 'utf-8');
            $result = $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($str, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
        }
    }
    return $result;
}

/**
 * 获取从服务器到 public 路径
 */
if (!function_exists("path_public")) {
    function path_public()
    {
        $url = public_path();
        $arrs = explode("\\", $url);
        foreach ($arrs as $key => $value) {
            if ($value == "public") {
                return 'http://' . getDomainName() . "/" . $arrs[$key - 2] . "/" . $arrs[$key - 1] . "/" . $arrs[$key] . "/";
            }
        }

    }
}

//*待用
function get_img_thumb_url($content = "")
{
    $pregRule = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/";
    $content = preg_replace($pregRule, '<img src="' . Url::getHost() . '${1}' . '">', $content);
    return $content;
}

if (!function_exists("pass_validate")) {
    /**
     * 检查用户账号密码是否正确
     * @param $request_name 用户名
     * @param $request_pass 用户密码
     * @return null
     */
    function pass_validate($request_name, $request_pass)
    {
        $admin = Admin::where('name', strtolower($request_name))->first();
        if (empty($admin)) {
            return null;
        }

        $key = md5($admin->validcode);
        $password = substr($key, 0, 16) . $request_pass . substr($key, 16, 16);

        if ($admin->password !== md5($password)) {
            return null;
        }
        return $admin;
    }
}

if (!function_exists("random_string")) {
    /**
     * @brief 随机生成字符串函数
     * @param int $len 要生成的长度
     * @param string $type 生成字符串的类型
     * @return String 随机生成字符
     */
    function random_string($len = 6, $type = 'mix')
    {
        $len = intval($len);
        if ($len > 90) $len = 90;
        $str = '';
        switch ($type) {
            case 'int':
                $templet = '012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789';
                break;
            case 'lowchar':
                $templet = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijkl';
                break;
            case 'upchar':
                $templet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKL';
                break;
            case 'char':
                $templet = 'abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyzamwz0379bhklqdklg482156smyew';
                break;
            default:
                $templet = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ~!@#$%^&*()_+-=[]{}:";<>,.?|';
                break;
        }
        $start = mt_rand(1, (90 - $len));
        $string = str_shuffle($templet);
        return substr($string, $start, $len);
    }
}

/**
 * @param $temp 三位运算符
 */
function threeOperator($temp)
{
    if (!empty($temp)) {
        if ($temp == 'undefined') {
            return "";
        }
        if ($temp == 'null') {
            return "";
        }
        return $temp;
    }
    return "";
}

/**
 * @param $province
 * @param $city
 * @param $county
 */
function get_Addr_str($province, $city, $county)
{
    $str = "";
    if (!empty($province)) {
        $str .= \App\Models\MArea::find($province)->name . ' ';

    }
    if (!empty($city)) {
        $str .= \App\Models\MArea::find($city)->name . ' ';
    }
    if (!empty($county)) {
        $str .= \App\Models\MArea::find($county)->name . ' ';
    }
    return $str;

}

function get_oneAddr($id)
{
    $result = \App\Models\MArea::find($id);
    if (!empty($result)) {
        return $result->name;
    } else {
        return "";
    }
}

/**
 * @param $vip
 * @return mixed  根据接口传过来的值 调整为我们需要的值
 */
function vip_change($vip)
{
    if ($vip == 0) {
        return \App\Models\MCustomer::$VIP0;
    } elseif ($vip == 1) {
        return \App\Models\MCustomer::$VIP1;
    } elseif ($vip == 2) {
        return \App\Models\MCustomer::$VIP2;
    } elseif ($vip == 3) {
        return \App\Models\MCustomer::$VIP3;
    }

}

/**
 * @param $vip
 * @return mixed  根据接口传过来的值 调整为我们需要的值
 */
function change_vip($vip)
{
    if ($vip == \App\Models\MCustomer::$VIP0) {
        return 0;
    } elseif ($vip == \App\Models\MCustomer::$VIP1) {
        return 1;
    } elseif ($vip == \App\Models\MCustomer::$VIP2) {
        return 2;
    } elseif ($vip == \App\Models\MCustomer::$VIP1) {
        return 3;
    }

}

///**
// * 根据订单ID获取物流公司信息
// * @param $oid  订单ID
// * @return mixed
// */
//function getExpressInfo($oid)
//{
//    $order = \App\Models\MOrder::find($oid);
//    $express = \App\Models\MExpressCompany::find($order->express_company_id);
//    return $express;
//}

if (!function_exists("getDataList")) {
    /**
     * 根据传入最小值 最大值 返回时间array()
     */
    function getDataList($startTime, $endTime, $cycleTime)
    {
        $arrayTime = array();
        while ($startTime <= $endTime) {
            $arrayTime[] = $startTime;
            $startTime += $cycleTime;
        }
        return $arrayTime;
    }
}

if (!function_exists('YearAndMonth')) {
    /**
     * 输出时间戳对应年月的时间戳
     */
    function YearAndMonth($time)
    {
        return strtotime(date("Y-m", $time));
    }
}

if (!function_exists('dateFormat')) {
    /**
     * 根据值判断返回日期格式形式
     */
    function dateFormat($method)
    {
        if ($method == 1) {
            return "Y-m-d H";
        } elseif ($method == 2) {
            return "Y-m-d";
        } elseif ($method == 3) {
            return "Y-m";
        }
    }
}

if (!function_exists('betweenMonth')) {
    /**
     * 输出时间戳相差月份
     */
    function betweenMonth($start, $end)
    {
        return $between = (date("Y", $end) - date("Y", $start)) * 12 + date("m", $end) - date('m', $start);
    }
}

if (!function_exists('getMonthList')) {
    /**
     * 根据相差的时间输出月份列表数组
     */
    function getMonthList($start, $end)
    {
        $monthTime = array();
        while ($start < $end) {
            $monthTime[] = $start;
            if (date("m", $start) < 12) {
                $start = strtotime(date('Y-m', $start) . "+1 month");
            } elseif (date("m", $start) == 12) {
                $start = strtotime(date('Y-01-01', $start) . "+1 year");
            }
        }

        $monthTime[] = $end;
        return $monthTime;
    }
}

if (!function_exists('isInArray')) {
    //判断一个数组元素是否在另一个数组中
    function isInArray($a, $b)
    {
        $c = array_diff($a, $b);
        $flag = empty($c) ? 1 : 0;
        if ($flag) {
            return true;
        } else {
            return false;
        }
    }
}

if (!function_exists('checkTime')) {
    /**
     * 检查时间是否为空或为NaN
     * 正确返回时间 错误为空
     */
    function checkTime($time)
    {
        if ($time != '' && $time != 'NaN') {
            return $time;
        } else {
            return '';
        }
    }
}

if (!function_exists('formatMoney')) {
    //金额保留2位小数
    function formatMoney($money)
    {
        return sprintf("%.2f", $money);
    }
}

if (!function_exists("getTableSize")) {
    /**
     * 获取sql文件大小文字描述
     *
     * @param string $size sql文件尺寸
     * @return string 返回文件大小文字描述
     */
    function getTableSize($size)
    {
        if ($size >= 1073741824) {
            return round($size / 1073741824 * 100) / 100 . ' Gb';
        } elseif ($size >= 1048576) {
            return round($size / 1048576 * 100) / 100 . ' Mb';
        } elseif ($size >= 1024) {
            return round($size / 1024 * 100) / 100 . ' Kb';
        } elseif ($size > 0) {
            return $size . ' B';
        } else {
            return "0 Kb";
        }
    }
}

if (!function_exists("modifyEnv")) {
    /**
     * 修改env文件配置
     * @param array $data
     */
    function modifyEnv(array $data)
    {
        $envPath = base_path() . DIRECTORY_SEPARATOR . '.env';

        $contentArray = collect(file($envPath, FILE_IGNORE_NEW_LINES));

        $contentArray->transform(function ($item) use ($data) {
            foreach ($data as $key => $value) {
                if (str_contains($item, $key)) {
                    return $key . '=' . $value;
                }
            }

            return $item;
        });

        $content = implode($contentArray->toArray(), "\n");

        \File::put($envPath, $content);
    }
}

if (!function_exists("hash_md5")) {
    /**
     * @brief 调用系统的MD5散列方式 主要用于用户密码加密
     * @param String $str
     * @param bool $validcode
     * @return String
     */
    function hash_md5($str, $validcode = false)
    {
        if ($validcode) {
            $key = md5($validcode);
            $str = substr($key, 0, 16) . $str . substr($key, 16, 16);
        }
        return md5($str);
    }
}

if (!function_exists("getGoodSalesId")) {
    /**
     * 参加所有活动的商品id
     * $class 不予计算的活动名称  不传所有活动都考虑
     */
    function getGoodSalesId($class = '')
    {
        $promGoodsId = getGoodId(\App\Models\MPromGoods::class);
        $bundingsId = [];
        $groupBysId = getGoodId(\App\Models\MGroupBuy::class);
        $flashSalesId = getGoodId(\App\Models\MFlashSale::class);
        $goods_id = array();
        if ($class == \App\Models\MPromGoods::class) {
            $goods_id = array_unique(array_merge($bundingsId, $groupBysId, $flashSalesId));
        } elseif ($class == \App\Models\MBundling::class) {
            $goods_id = [];
//            $goods_id = array_unique(array_merge($promGoodsId, $groupBysId, $flashSalesId));
        } elseif ($class == \App\Models\MGroupBuy::class) {
            $goods_id = array_unique(array_merge($promGoodsId, $bundingsId, $flashSalesId));
        } elseif ($class == \App\Models\MFlashSale::class) {
            $goods_id = array_unique(array_merge($promGoodsId, $bundingsId, $groupBysId));
        } else {
            $goods_id = array_unique(array_merge($promGoodsId, $bundingsId, $groupBysId, $flashSalesId));
        }

        return $goods_id;
    }
}

if (!function_exists("getGoodId")) {
    /**
     * 某一活动的商品id数组
     */
    function getGoodId($class)
    {
        $objs = $class::all();
        $ids = array();
        if (!$objs->isEmpty()) {
            foreach ($objs as $obj) {
                $good_ids = explode(',', $obj->goods_id);
                $ids = array_unique(array_merge($ids, $good_ids));
            }
        }
        return $ids;
    }
}

if (!function_exists("checkMoneyOk")) {
    /**
     * 检查金额是否合法并且保留两位小数
     */
    function checkMoneyOk($money)
    {
        //检查输入的金额是否合法
        if (!is_numeric($money) || $money <= 0 || $money > 999999999) {
            return false;
        }
        $money = sprintf("%.2f", $money); //保留两位小数

        return $money;
    }
}

if (!function_exists("goodsLink")) {
    /**
     * 商品链接
     * $id 商品id
     */
    function goodsLink($id)
    {
        if ($id) {
            return env("APP_URL") . "index/goods.html?id=" . $id;
        } else {
            return '';
        }
    }
}

if (!function_exists("get_client_ip ")) {
    /**
     * 获取终端ip
     */
    function get_client_ip()
    {
        $ip = '';
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        $ip_arr = explode(',', $ip);
        return $ip_arr[0];
    }
}

if (!function_exists("saveImgPath")) {
    /**
     * 存储单个图片到是数据库判断：服务器还是七牛上传
     */
    function saveImgPath($img)
    {
        $path = '';
        if ($img) {
            $check = explode('.', $img);
            if (in_array(end($check), App\Utils\ComUtil::$ext)) { //服务器上传
                $path = strstr($img, "files");
            } else { //七牛上传
                $ins = explode('/', $img);
                $path = end($ins);
            }
        }

        return $path;
    }
}

if (!function_exists("saveImgs")) {
    /**
     * 存储多个图片到数据库判断：服务器还是七牛上传
     */
    function saveImgs($imgs)
    {
        $arr = [];
        $imgs = json_decode($imgs, true); //图片处理
        if ($imgs) {
            foreach ($imgs as $pic) {
                $arr[] = saveImgPath($pic);
            }
        }
        return serialize($arr);
    }
}

if (!function_exists('judgeServerOrQiniu')) {
    /**
     * 返回图片到前端判断：服务器还是七牛图
     */
    function judgeServerOrQiniu($img)
    {
        $absolutePath = '';
        if ($img) {
            $check = explode('.', $img);
            if (in_array(end($check), App\Utils\ComUtil::$ext)) { //服务器上传
                $absolutePath = asset($img);
            } else { //七牛上传
                $absolutePath = cv('qiniu.Domain') . $img;
            }
        }

        return $absolutePath;
    }
}